package com.yiren.backstage.communication.services.impl;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.yiren.backstage.communication.interfaces.DataCallback;
import com.yiren.backstage.communication.services.AbstractPortService;
import com.yiren.backstage.communication.utils.BluetoothUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Time:2021/12/23 15:40
 * Author:xiaozan
 * Description:蓝牙通讯
 */
public class BluetoothPortServiceImpl extends AbstractPortService {

    private String name;
    private String address;
    private BluetoothSocket socket;

    public BluetoothPortServiceImpl() {
        super();
    }

    @Override
    public void setParam(String key, Object obj) {
            name = (String) key;
            address = (String) obj;
    }

    @Override
    public boolean start(){
        try {
            BluetoothDevice device = BluetoothUtil.getInstance().theBluetoothDevice(name, address);
            socket = device.createRfcommSocketToServiceRecord(BluetoothUtil.MY_UUID);
            socket = (BluetoothSocket) device.getClass().getMethod("createRfcommSocket",new Class[]{int.class}).invoke(device,1);
            socket.connect();
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
       return false;
    }

    @Override
    public void stop() throws Exception {
        super.stop();
        if (socket != null) {
            socket.close();
            socket = null;
        }
    }

    @Override
    public String read(byte[] data, int offset, int size) throws IOException {
        return super.read(data,offset,size);
    }

    @Override
    public void write(byte[] data) throws IOException {
        super.write(data);
    }
}
